#!/bin/bash
# changedailybackup: change the back folder to the current date
# version 0.1-beta
# Scriptter: Mohammed Shannaq, m.shannaq@gmail.com , www.phpspiders.com
#            Nov-2007
# Usage: changedailybackup.sh [basebackupfolder]

PATH=/bin:/usr/bin:/usr/local/bin
echo "Change Backup Daily folder to the day date script"
echo "script version 0.1-beta"
echo "dont by: Mohammed Shannaq for CPanel Servers"

ROOT_UID=0     # Only users with $UID 0 have root privileges.
BASEBACKUP='/backup'	#base default backup folderstarted started with / (physical path)
CPBACKUP='cpbackup'	#cpbackup folder name (cpanel use the name cpbacup by default)
DAILYFOLDER='daily';
script_parameters="-h"
today_date=`date '+%d%b%Y'`;
#ERROR NOS
E_WRONG_ARGS=65
E_XCD=66       # Can't change directory?
E_NOTROOT=67   # Non-root exit error.


# Run as root, of course.
if [ "$UID" -ne "$ROOT_UID" ]
then
  echo "Must be root to run this script."
  exit $E_NOTROOT
fi 

if [ -n "$1" ]
# Test if command line argument present (non-empty).
then
  basebackupfolder=$1
else  
  basebackupfolder=$BASEBACKUP  # Default, if not specified on command line
fi

cd $basebackupfolder
if [ `pwd` != "$basebackupfolder" ]  # or   if [ "$PWD" != "$basebackupfolder" ]
                            # Not in $basebackupfolder
then
  echo "Can't change to $basebackupfolder, make sure that you entered the correct base backup folder which contains cpbackup folder"
  exit $E_XCD
fi  # Doublecheck if in right directory, before messing with log file.

cd $CPBACKUP
if [ `pwd` != "$basebackupfolder/$CPBACKUP" ]
then
   echo "Can't change to ($CPBACKUP) folder, make sure that the folder is exists on this path ($basebackupfolder)"
   exit $E_XCD
fi

#cd $DAILYFOLDER
#if [ `pwd` != "$basebackupfolder/$CPBACKUP/$DAILYFOLDER" ]
#then
#   echo "Can't change to ($DAILYFOLDER) folder, make sure that the folder is exists on this path ($basebackupfolder/$CPBACKUP)"
#   exit $E_XCD
#fi
 
#i will check the ps -aux to see if there is any backup progress is going on
sleepfor=60
psres=`ps aux | grep pkgacct | wc -l`


while [ $psres -gt 1 ]
do
echo "I found $psres proccess using pkgacct, so i will sleep for $sleepfor seconds and check again ..."
sleep $sleepfor
psres=`ps aux | grep pkgacct | wc -l`
done
if test -d $basebackupfolder/$CPBACKUP/$DAILYFOLDER
then
#echo "$basebackupfolder/$CPBACKUP/$DAILYFOLDER is a folder"
#now i will rename it
mv $basebackupfolder/$CPBACKUP/$DAILYFOLDER $basebackupfolder/$CPBACKUP/$today_date
echo "I rename the folder $basebackupfolder/$CPBACKUP/$DAILYFOLDER to $basebackupfolder/$CPBACKUP/$today_date"
else
echo "$basebackupfolder/$CPBACKUP/$DAILYFOLDER folder is not exists, so i did not change anything"
exit $E_XCD
fi
exit 0
